package com.cloud.parammanage.common.service.impl;

import cn.hutool.cron.timingwheel.SystemTimer;
import cn.hutool.cron.timingwheel.TimerTask;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.parammanage.common.entity.ParamConfig;
import com.cloud.parammanage.common.mapper.ParamConfigMapper;
import com.cloud.parammanage.common.service.ParamConfigService;
import javax.annotation.PostConstruct;
import org.cloud.core.redis.RedisUtil;
import org.springframework.stereotype.Service;

@Service
public class ParamConfigServiceImpl extends ServiceImpl<ParamConfigMapper, ParamConfig> implements ParamConfigService {

    @Override
    public int insertSelective(ParamConfig record) {
        return baseMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(ParamConfig record) {
        int result = baseMapper.updateByPrimaryKeySelective(record);
        ParamConfig cacheRecord = lambdaQuery().eq(ParamConfig::getId, record.getId()).one();
        RedisUtil.single().set(CONFIG_PRAGMA_CACHE_KEY + cacheRecord.getConfigCode(), cacheRecord);
        return result;
    }

    @Override
    public void refreshCache() {
        lambdaQuery().list().forEach(paramConfig -> RedisUtil.single().set(CONFIG_PRAGMA_CACHE_KEY + paramConfig.getConfigCode(), paramConfig));
    }

    @Override
    public ParamConfig get(String code) {
        return RedisUtil.single().get(CONFIG_PRAGMA_CACHE_KEY + code);
    }

    @PostConstruct
    public void init() {
        SystemTimer systemTimer = new SystemTimer();
        systemTimer.start();
        systemTimer.addTask(new TimerTask(this::refreshCache, 5000));
    }
}

